// ObserverPatternV2.cpp : Defines the entry point for the console application.
// 12/8/2011

#include "stdafx.h"

using namespace std;

void generateEvents();

Notifier* theNotifier;

int main(int argc, char* argv[])
{

	theNotifier = Notifier::getInstance();
	// Create two observers to test both constructors
	CountKeys *keyEventCounter = new CountKeys();
	CountKeys *keyEventCounter1 = new CountKeys("Key Counter 1");

	// Subscribe to the key events
	if (keyEventCounter->subscribe(KEY_EVENT)) cout << "[Main] Observer registered." << endl;
	// Generate the key events
	generateEvents();

	// Unsubscribe to the key events
	if(keyEventCounter->unsubscribe(KEY_EVENT)) cout << "[Main] Observer removed." << endl;

	// We would have a memory leak bug here if we didn't delete the previous key event counter.
	delete keyEventCounter;

	// Replace the deleted observer with a new key counter
	keyEventCounter = new CountKeys("Key Counter 2");
	
	// Subscribe the new observer to both key and class events
	if (keyEventCounter->subscribe(KEY_EVENT)) cout << "[Main] New key event observer registered." << endl;
	if(keyEventCounter->subscribe(CLASS_EVENT)) cout << "[Main] New class observer registered." << endl;

	// Generate the key events
	generateEvents();

	// Unsubcribe from key events only
	if (keyEventCounter->unsubscribe(KEY_EVENT)) cout << "[Main] Observer removed." << endl;

	// Subscribe the second observer to both key and class events. Notice class events was subscribed using the notifier instead of the observer to demonstate both subscibing methods.
	if (keyEventCounter1->subscribe(CLASS_EVENT)) cout << "[Main] New class event observer registered." << endl;
	if (theNotifier->subscribe(keyEventCounter1, KEY_EVENT)) cout << "[Main] New key event observer registered." << endl;

	// Generate the key events
	generateEvents();

	// Generate a class event
	theNotifier->LogEvent(CLASS_EVENT, "PRINT");

	//should always have a delete for every new
	delete keyEventCounter;
	delete keyEventCounter1;

	return 0;
}

void generateEvents()
{
	string inString;
	cout << endl << "Enter a string: ";
	//Get a string to parse
	getline(cin, inString);
	//Generate key events
	cout << endl;
	for (int i = 0; i < int(inString.size()); i++)
	{
		theNotifier->LogEvent(KEY_EVENT, inString.substr(i,1));
	}
	cout << endl;
}


